import { marked } from "marked";
import {
  Col,
  Row,
  Input,
  Select,
  Button,
  DatePicker,
  Drawer,
  List,
  message,
  Popover,
} from "antd";
import React, { useEffect, useState } from "react";
import "./Addarticle.css";
import axios from "axios";
import servicePath from "../../config/apiUrl";

const Addarticle = (props) => {
  console.log(props);
  const [articleId, setArticleId] = useState(0); // 文章的ID，如果是0说明是新增加，如果不是0，说明是修改
  const [articleTitle, setArticleTitle] = useState(""); //文章标题
  const [articleContent, setArticleContent] = useState(""); //markdown的编辑内容
  const [markdownContent, setMarkdownContent] = useState("预览内容"); //html内容
  const [introducemd, setIntroducemd] = useState(); //简介的markdown内容
  const [introducehtml, setIntroducehtml] = useState("文章简介"); //简介的html内容
  const [showDate, setShowDate] = useState(); //发布日期
  const [selectedType, setSelectType] = useState(1); //选择的文章类别
  const [visible, setVisible] = useState(false); //快捷键规则
  const [preview, setPreview] = useState(true); //是否显示预览区

  marked.setOptions({
    renderer: new marked.Renderer(),
    gfm: true, //允许标准的markdown
    pedantic: false, //不纠正不良错误
    sanitize: false, //过滤已经输出任何标签
    tables: true, //支持表格语法
    breaks: false, //允许回车换行
    smartLists: true, //时髦的列表，升级的列表
    smartypants: false, //新的标点，比如在引用语法中加入破折号
  });
  // 文章内容
  const changeContent = (e) => {
    let value = e.target.value;
    setArticleContent(value);
    let html = marked(value);
    setMarkdownContent(html);
  };
  // 文章简介
  const onChangeIntroduce = (e) => {
    let value = e.target.value;
    setIntroducemd(value);
    let html = marked(value);
    setIntroducehtml(html);
  };
  // 快捷键规则
  const showDrawer = () => {
    setVisible(true);
  };
  //关闭快捷键规则
  const onClose = () => {
    setVisible(false);
  };
  //显示预览区
  const displayPreview = () => {
    setPreview(!preview);
  };
  //快捷键规则数据
  const data = [
    "# 一级标题",
    "## 二级标题",
    "### 三级标题",
    "#####  五级标题",
    "1.  有序列表",
    "-   无序列表",
    ">   引用",
    "` 代码 `   代码",
    "**文字加粗",
    "*斜体",
    "~下划线",
    "~~删除线",
  ];
  //选中的标签
  const handleChange = (e) => {
    setSelectType(e.key);
  };
  //保存文章
  const saveArticle = () => {
    var dataProps = {};
    dataProps.id = Math.round(Math.random() * 1000);
    dataProps.type_id = selectedType;
    dataProps.title = articleTitle;
    dataProps.article_content = articleContent;
    dataProps.introduce = introducemd;
    dataProps.add_time = showDate;
    if (articleId === 0) {
      axios({
        method: "post",
        url: servicePath.saveArticle,
        // url:"http://127.0.0.1:7001/admin/addArticle",
        data: dataProps,
        header: { "Access-Control-Allow-Origin": "*" },
        withCredentials: true,
      }).then((res) => {
        setArticleId(res.data.insertId);
        if (res.data.insertSuccess) {
          message.success("暂存成功");
        } else {
          message.error("暂存失败");
        }
      });
      console.log(articleId);
    } else {
      dataProps.id = articleId;
      axios({
        method: "post",
        url: servicePath.updateSaveArticle,
        header: { "Access-Control-Allow-Origin": "*" },
        data: dataProps,
        withCredentials: true,
      }).then((res) => {
        console.log(res.data.isUpdateScuccess);
        if (res.data.isUpdateScuccess) {
          message.success("暂存成功");
        } else {
          message.error("暂存失败");
        }
      });
    }
  };
  // 发布文章
  const sumbitArticle = () => {
    // marked();
    if (!articleTitle) {
      message.error("未写文章标题");
      return false;
    }
    if (!articleContent) {
      message.error("内容不能为空");
      return false;
    }
    if (!selectedType) {
      message.error("文章标签未选");
      return false;
    }
    if (!showDate) {
      message.error("时间未选中");
      return false;
    }
    var dataProps = {};
    dataProps.id = Math.round(Math.random() * 1000);
    dataProps.type_id = selectedType;
    dataProps.title = articleTitle;
    dataProps.article_content = articleContent;
    dataProps.introduce = introducemd;
    dataProps.add_time = showDate;
    if (articleId === 0) {
      console.log("articleId=:" + articleId);
      axios({
        method: "post",
        url: servicePath.addArticle,
        // url:"http://127.0.0.1:7001/admin/addArticle",
        data: dataProps,
        header: { "Access-Control-Allow-Origin": "*" },
        withCredentials: true,
      }).then((res) => {
        setArticleId(res.data.insertId);
        if (res.data.insertSuccess) {
          message.success("发布成功");
        } else {
          message.error("发布失败");
        }
      });
    } else {
      //修改文章
      console.log("articleId:" + articleId);
      dataProps.id = articleId;
      axios({
        method: "post",
        url: servicePath.updateArticle,
        header: { "Access-Control-Allow-Origin": "*" },
        data: dataProps,
        withCredentials: true,
      }).then((res) => {
        console.log(res.data);
        if (res.data.isUpdateScuccess) {
          message.success("文章修改成功");
        } else {
          message.error("修改失败");
        }
      });
    }
  };
  //编辑文章
  const editArtcile = (id) => {
    axios({
      method: "get",
      url: servicePath.editArtcile + id,
      header: { "Access-Control-Allow-Origin": "*" },
      withCredentials: true,
    }).then((res) => {
      console.log(res, "res");
      setArticleTitle(res.data.data[0].title);
      setArticleContent(res.data.data[0].article_content);
      let html = marked(res.data.data[0].article_content);
      setMarkdownContent(html);
      setIntroducemd(res.data.data[0].introduce);
      let tmpInt = marked(res.data.data[0].introduce);
      setIntroducehtml(tmpInt);
      setShowDate(res.data.data[0].add_time);
      setSelectType(res.data.data[0].type_id);
    });
  };
  //编辑草稿文章
  const editDrafts = (id) => {
    axios({
      method: "get",
      url: servicePath.editDrafts + id,
      header: { "Access-Control-Allow-Origin": "*" },
      withCredentials: true,
    }).then((res) => {
      console.log(res, "res");
      setArticleTitle(res.data.data[0].title);
      setArticleContent(res.data.data[0].article_content);
      let html = marked(res.data.data[0].article_content);
      setMarkdownContent(html);
      setIntroducemd(res.data.data[0].introduce);
      let tmpInt = marked(res.data.data[0].introduce);
      setIntroducehtml(tmpInt);
      setShowDate(res.data.data[0].add_time);
      setSelectType(res.data.data[0].type_id);
    });
  };

  useEffect(() => {
    let url = window.location.href;
    let tmpid = url.split("/")[5];
    if (tmpid) {
      editArtcile(tmpid);
      editDrafts(tmpid);
    }
  }, []);
  return (
    <>
      <div
        className="site-layout-background"
        style={{ padding: 24, minHeight: 360 }}
      >
        <div>
          <Row gutter={5}>
            <Col span={20}>
              <Row gutter={10}>
                <Col span={20}>
                  <Input
                    placeholder="博客标题"
                    size="large"
                    value={articleTitle}
                    onChange={(e) => {
                      setArticleTitle(e.target.value);
                    }}
                  />
                </Col>
                <Col span={4}>
                  &nbsp;
                  <Select
                    labelInValue
                    defaultValue={{ value: "标签" }}
                    style={{ width: 120 }}
                    onChange={handleChange}
                  >
                    <Select.Option key="1" value="生活">
                      生活
                    </Select.Option>
                    <Select.Option key="2" value="科技">
                      科技
                    </Select.Option>
                    <Select.Option key="3" value="美食">
                      美食
                    </Select.Option>
                    <Select.Option key="4" value="艺术">
                      艺术
                    </Select.Option>
                    <Select.Option key="5" value="娱乐">
                      娱乐
                    </Select.Option>
                  </Select>
                  &nbsp;&nbsp;
                  <Popover title="预览">
                    <span className="preview" onClick={displayPreview}>
                      {preview ? (
                        <svg
                          t="1652520949141"
                          class="icon"
                          viewBox="0 0 1024 1024"
                          version="1.1"
                          xmlns="http://www.w3.org/2000/svg"
                          p-id="1408"
                          width="20"
                          height="20"
                        >
                          <path
                            d="M242.526316 215.578947h431.157895v53.894737H242.526316V215.578947z m431.157895 269.473685H242.526316V431.157895h431.157895v53.894737z m323.368421 323.368421c0 88.279579-144.761263 215.578947-323.368421 215.578947s-323.368421-127.353263-323.368422-215.578947a164.055579 164.055579 0 0 1 53.894737-107.789474H242.526316v-53.894737h215.578947v10.778947a388.042105 388.042105 0 0 1 377.263158-28.725894V53.894737H80.842105v862.315789h323.368421v53.894737H26.947368V0h862.31579v658.054737A208.357053 208.357053 0 0 1 997.052632 808.421053z m-134.736843-107.789474H835.368421v-14.928842A356.675368 356.675368 0 0 0 673.684211 646.736842c-148.857263 0-269.473684 91.136-269.473685 161.684211 0 66.182737 120.616421 161.684211 269.473685 161.68421s269.473684-95.501474 269.473684-161.68421a149.989053 149.989053 0 0 0-80.842106-107.789474zM673.684211 916.210526a107.789474 107.789474 0 1 1 107.789473-107.789473 107.789474 107.789474 0 0 1-107.789473 107.789473z m0-161.68421a53.894737 53.894737 0 1 0 53.894736 53.894737 53.894737 53.894737 0 0 0-53.894736-53.894737z"
                            fill="#8a8a8a"
                            p-id="1409"
                          ></path>
                        </svg>
                      ) : (
                        <svg
                          t="1652521223480"
                          class="icon"
                          viewBox="0 0 1024 1024"
                          version="1.1"
                          xmlns="http://www.w3.org/2000/svg"
                          p-id="1694"
                          width="20"
                          height="20"
                        >
                          <path
                            d="M242.526316 215.578947h431.157895v53.894737H242.526316V215.578947z m431.157895 269.473685H242.526316V431.157895h431.157895v53.894737z m323.368421 323.368421c0 88.279579-144.761263 215.578947-323.368421 215.578947s-323.368421-127.353263-323.368422-215.578947a164.055579 164.055579 0 0 1 53.894737-107.789474H242.526316v-53.894737h215.578947v10.778947a388.042105 388.042105 0 0 1 377.263158-28.725894V53.894737H80.842105v862.315789h323.368421v53.894737H26.947368V0h862.31579v658.054737A208.357053 208.357053 0 0 1 997.052632 808.421053z m-134.736843-107.789474H835.368421v-14.928842A356.675368 356.675368 0 0 0 673.684211 646.736842c-148.857263 0-269.473684 91.136-269.473685 161.684211 0 66.182737 120.616421 161.684211 269.473685 161.68421s269.473684-95.501474 269.473684-161.68421a149.989053 149.989053 0 0 0-80.842106-107.789474zM673.684211 916.210526a107.789474 107.789474 0 1 1 107.789473-107.789473 107.789474 107.789474 0 0 1-107.789473 107.789473z m0-161.68421a53.894737 53.894737 0 1 0 53.894736 53.894737 53.894737 53.894737 0 0 0-53.894736-53.894737z"
                            fill="#1296db"
                            p-id="1695"
                          ></path>
                        </svg>
                      )}
                    </span>
                  </Popover>
                </Col>
              </Row>
              <br />
              <Row gutter={10}>
                <Col span={preview ? 12 : 24}>
                  <Input.TextArea
                    className="markdown-content"
                    rows={35}
                    placeholder="文章内容"
                    value={articleContent}
                    onChange={changeContent}
                    onPressEnter={changeContent} //按下回车键的回调
                  />
                </Col>

                <Col span={preview ? 12 : 0}>
                  <div
                    dangerouslySetInnerHTML={{ __html: markdownContent }}
                    className="show-html"
                  ></div>
                </Col>
              </Row>
            </Col>
            <Col span={4}>
              <Col span={6}>
                <Row>
                  <Col span={24}>
                    <Button size="large" onClick={saveArticle}>
                      暂存文章
                    </Button>
                    &nbsp;
                    <Button type="primary" size="large" onClick={sumbitArticle}>
                      发布文章
                    </Button>
                    <br />
                  </Col>
                </Row>
              </Col>
              <Col span={24}>
                <br />
                <Input.TextArea
                  rows={4}
                  placeholder="文章简介"
                  value={introducemd}
                  onChange={onChangeIntroduce}
                  onPressEnter={onChangeIntroduce}
                />
                <br />
                <br />
                <div
                  className="introduce-html"
                  dangerouslySetInnerHTML={{ __html: introducehtml }}
                ></div>
              </Col>

              <Col span={12}>
                <div className="date-select">
                  <DatePicker
                    placeholder="发布日期"
                    size="large"
                    onChange={(date, dateString) => setShowDate(dateString)}
                  />
                </div>
              </Col>
              <br />
              <Button type="primary" onClick={showDrawer}>
                快捷键规则
              </Button>
              <Drawer
                mask={false}
                title="快捷键规则"
                placement="right"
                onClose={onClose}
                visible={visible}
              >
                <List
                  size="large"
                  bordered
                  dataSource={data}
                  renderItem={(item) => <List.Item>{item}</List.Item>}
                />
              </Drawer>
            </Col>
          </Row>
        </div>
      </div>
    </>
  );
};

export default Addarticle;
